﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;
using CrmCustomizationsExcelAddIn.Data;
using CrmCustomizationsExcelAddIn.Helper;
using Microsoft.Xrm.Sdk.Metadata;
using Microsoft.Xrm.Sdk.Messages;



namespace CrmCustomizationsExcelAddIn
{
    public partial class CrmCreateConfirm : Form
    {
        IEnumerable<CrmOperation> operationList;

        public CrmCreateConfirm()
        {
            InitializeComponent();
        }

        private void Confirm_Click(object sender, EventArgs e)
        {
            bgwCrmOperations.WorkerReportsProgress = true;
            bgwCrmOperations.RunWorkerAsync();
            prbCrmOperationStatus.Visible = true;
        }


        private void Cancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }




        private void ShowGridData( bool showResult)
        {
            
            dgvCrmOperation.DataSource = operationList.ToList();
            dgvCrmOperation.Columns["operationType"].HeaderText = "Operation Type";
            dgvCrmOperation.Columns["operationType"].DisplayIndex = 0;
            dgvCrmOperation.Columns["previewString"].HeaderText = "Preview String";
            dgvCrmOperation.Columns["previewString"].DisplayIndex = 1;
            dgvCrmOperation.Columns["executeOperation"].HeaderText = "Execute Operation";
            dgvCrmOperation.Columns["executeOperation"].DisplayIndex = 2;
            dgvCrmOperation.Columns["operationSucceded"].HeaderText = "Operation Succeed";
            dgvCrmOperation.Columns["operationSucceded"].DisplayIndex = 3;
            dgvCrmOperation.Columns["exceptionString"].HeaderText = "Exception";
            dgvCrmOperation.Columns["exceptionString"].DisplayIndex = 4;
            //set the col size
            dgvCrmOperation.Columns["operationType"].MinimumWidth = 10;
            dgvCrmOperation.Columns["operationType"].ReadOnly = true;
            dgvCrmOperation.Columns["previewString"].MinimumWidth = 300;
            dgvCrmOperation.Columns["previewString"].ReadOnly = true;
            dgvCrmOperation.Columns["operationSucceded"].MinimumWidth = 20;
            dgvCrmOperation.Columns["operationSucceded"].ReadOnly = true;
            dgvCrmOperation.Columns["exceptionString"].MinimumWidth = 200;
            dgvCrmOperation.Columns["exceptionString"].ReadOnly = true;
            dgvCrmOperation.Columns["orgRequest"].Visible = false;
            dgvCrmOperation.Columns["opertionTarget"].Visible = false;
            dgvCrmOperation.Columns["orgResponse"].Visible = false;
            if (!showResult)
            {
                dgvCrmOperation.Columns["executeOperation"].Visible = true;
                dgvCrmOperation.Columns["operationSucceded"].Visible = false;
                dgvCrmOperation.Columns["exceptionString"].Visible = false;
            }
            else
            {
                dgvCrmOperation.Columns["executeOperation"].Visible = false;
                dgvCrmOperation.Columns["operationSucceded"].Visible = true;
                dgvCrmOperation.Columns["exceptionString"].Visible = true;
            }
            dgvCrmOperation.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
            ////set the image
            //dgvCrmOperation.Columns["operationSucceded"].Visible = false;
            //DataGridViewImageColumn imageCol = new DataGridViewImageColumn();
            //imageCol.Name = "operationSucceded";
            //imageCol.SortMode = DataGridViewColumnSortMode.NotSortable;
            //dgvCrmOperation.Columns.Add(imageCol); 

            //foreach (DataGridViewRow row in dgvCrmOperation.Rows)          
            // {
            //     if (row.Cells["operationSucceded"].Value != null)      
            // {
            //     if (Convert.ToBoolean(row.Cells["operationSucceded"].Value))    
            //         {                         
            //             row.Cells["operationSucceded"].Value = trueImg;         
            //         }                  
            //         else                 
            //         {
            //             row.Cells["operationSucceded"].Value = trueImg;                          
            //         }                    
            //     }          
            // } 
        }



        private void CrmCreateConfirm_Load(object sender, EventArgs e)
        {
            prbCrmOperationStatus.Visible = false;
            ExcelSheetInfo currentsheet = GlobalApplicationData.Instance.eSheetsInfomation.getCurrentSheet();
            string name;
            ExcelSheetInfo.ExcelSheetType type;
            string orgprefix;
            int language;
            if (Globals.CrmAddIn.excelHelper.readSettingRow(currentsheet.excelsheet, out name, out type, out orgprefix, out language))
            {
                currentsheet.orgPrefix = orgprefix;
                currentsheet.language = language;
            }

            if (currentsheet != null)
            {
                operationList = generateOperationCurrentSheet(currentsheet);
                if (operationList != null)
                {
                    ShowGridData(false);
                }
            }
        }

        private IEnumerable<CrmOperation> generateOperationCurrentSheet(ExcelSheetInfo currentSheet)
        {
            ExcelMatrix matrix;
            switch (currentSheet.sheetType)
            {
                case ExcelSheetInfo.ExcelSheetType.attribute:
                    matrix = Globals.CrmAddIn.excelHelper.getExcelDataMatrix(currentSheet.excelsheet, ExcelColumsDefinition.MAXNUMBEROFCOLUMN, ExcelColumsDefinition.MAXNUMBEROFATTRIBUTE, ExcelColumsDefinition.SCHEMANAMEEXCELCOL);
                    AttributeRequestGenerator reqGeneratorHelper = new AttributeRequestGenerator((AttributeExcelSheetsInfo)currentSheet ,  GlobalApplicationData.Instance.optionSetData);
                    return reqGeneratorHelper.generateCrmOperationRequest(matrix);
                case ExcelSheetInfo.ExcelSheetType.optionSet:
                    matrix = Globals.CrmAddIn.excelHelper.getExcelDataMatrix(currentSheet.excelsheet, ExcelColumsDefinition.MAXNUMBEROFCOLUMN, ExcelColumsDefinition.MAXNUMBEROFATTRIBUTE, ExcelColumsDefinition.OPTIONSETVALUEEXCELCOL);
                    OptionSetRequestGenerator optGenerator = new OptionSetRequestGenerator((OptionSetExcelSheetsInfo)currentSheet);
                    return optGenerator.generateCrmOperationRequest(matrix);
                case ExcelSheetInfo.ExcelSheetType.entity:
                     matrix = Globals.CrmAddIn.excelHelper.getExcelDataMatrix(currentSheet.excelsheet, ExcelColumsDefinition.MAXNUMBEROFCOLUMN, ExcelColumsDefinition.MAXNUMBEROFATTRIBUTE, ExcelColumsDefinition.ENTITYSCHEMANAMEEXCELCOL);
                     EntityRequestGenerator entGenerator = new EntityRequestGenerator((EntityExcelSheetsInfo)currentSheet);
                     return entGenerator.generateCrmOperationRequest(matrix);
                case ExcelSheetInfo.ExcelSheetType.view:
                     MessageBox.Show("The view editor feature is released as Alpha Version. Please ensure to back up your CRM solution and report any issue on Codeplex project page.");
                     matrix = Globals.CrmAddIn.excelHelper.getExcelDataMatrix(currentSheet.excelsheet, ExcelColumsDefinition.MAXNUMBEROFCOLUMN, ExcelColumsDefinition.MAXNUMBEROFATTRIBUTE, ExcelColumsDefinition.VIEWATTRIBUTENAME);
                     return ViewXml.generateCrmOperationRequest(matrix, (ViewExcelSheetsInfo)currentSheet);
                case ExcelSheetInfo.ExcelSheetType.form:
                     MessageBox.Show("Forms are read only");
                     this.Close();
                     break;

            }
            return null;
        }

        private void lstChangePreview_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void btn_CloseClearSheet_Click(object sender, EventArgs e)
        {
            ExcelSheetInfo currentsheet = GlobalApplicationData.Instance.eSheetsInfomation.getCurrentSheet();
            if (currentsheet != null)
            {
                switch (currentsheet.sheetType)
                {
                    case ExcelSheetInfo.ExcelSheetType.attribute:
                        {
                            EntityMetadata currentEntity = Globals.CrmAddIn.crmOpHelper.RetriveEntityAtrribute(((AttributeExcelSheetsInfo)GlobalApplicationData.Instance.eSheetsInfomation.getCurrentSheet()).entityMedata.LogicalName);
                            ((AttributeExcelSheetsInfo)GlobalApplicationData.Instance.eSheetsInfomation.getCurrentSheet()).entityMedata = currentEntity;
                            IEnumerable<string> formAttr = Globals.CrmAddIn.crmOpHelper.GetAttributeOfTheMainForm(currentEntity.ObjectTypeCode.Value);
                            Globals.CrmAddIn.excelHelper.refreshAttributeSheeet(GlobalApplicationData.Instance.eSheetsInfomation.getCurrentSheet(), currentEntity, GlobalApplicationData.Instance.allEntities,formAttr);
                            break;
                        }
                    case ExcelSheetInfo.ExcelSheetType.optionSet:
                        {
                            OptionSetExcelSheetsInfo currentOption = (OptionSetExcelSheetsInfo)GlobalApplicationData.Instance.eSheetsInfomation.getCurrentSheet();
                            EntityMetadata currentEntity = Globals.CrmAddIn.crmOpHelper.RetriveEntityAtrribute(currentOption.parentAttribute.EntityLogicalName);
                            IEnumerable<AttributeMetadata> currentOpt = currentEntity.Attributes.Where(x => x.MetadataId.ToString() == currentOption.objectName);
                            if (currentOpt.Count() > 0)
                            {
                                currentOption.optionData = ((PicklistAttributeMetadata)currentOpt.First()).OptionSet;
                            }
                            break;
                        }
                    case ExcelSheetInfo.ExcelSheetType.view:
                        {
                            GlobalOperations.RefreshCurrentViewSheet();
                            break;
                        }
                }
            }
            this.Close();

        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {

        }

        private void bgwCrmOperations_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            int i = 0;
            foreach (var item in operationList)
            {
                if (item.executeOperation)
                {
                    Globals.CrmAddIn.crmOpHelper.executeOpertionsCrm(item);
                    i++;
                }
                worker.ReportProgress((int)(((double)i / operationList.Count()) * 100));
            }

            ExcelSheetInfo currentsheet = GlobalApplicationData.Instance.eSheetsInfomation.getCurrentSheet();
            if (currentsheet != null)
            {
                switch (currentsheet.sheetType)
                {
                    case ExcelSheetInfo.ExcelSheetType.view:
                        {
                            ViewExcelSheetsInfo viewSheet = (ViewExcelSheetsInfo)currentsheet;
                            if (viewSheet.isNew == true && operationList.First().operationSucceded)
                            {
                                if (operationList.Count() > 0 && operationList.First().orgResponse != null && operationList.First().orgResponse is CreateResponse)
                                {
                                    viewSheet.viewId = ((CreateResponse)operationList.First().orgResponse).id;
                                }
                                viewSheet.isNew = false;
                            }
                            break;
                        }
                }
            }

        }

        private void bgwCrmOperations_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            prbCrmOperationStatus.Value = e.ProgressPercentage;
        }

        private void bgwCrmOperations_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            ShowGridData(true);
        }
    }
}
